<template>
  <div class="comment-pub">
    <van-field class="post-field"
      v-model.trim="message"
      rows="2"
      autosize
      type="textarea"
      maxlength="50"
      placeholder="请输入留言"
      show-word-limit />
    <van-button class='post-btn'
      @click="onPubComment"
      :disabled="!message.length">发布</van-button>
  </div>
</template>

<script>
import { publishComment } from '@/api/comment'
export default {
  name: 'CommentPub',
  components: {},
  props: {
    target: {
      type: [Number, String, Object],
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      default: null
    }
  },
  data () {
    return {
      message: ''
    }
  },
  methods: {
    async onPubComment () {
      this.$toast.loading({
        message: '发布中...',
        forbidClick: true
      })
      try {
        const { data: res } = await publishComment({
          target: this.target,
          content: this.message,
          art_id: this.articleId ? this.articleId : null
        })
        console.log(res.data)
        // 1、关闭弹层 向父组件通信 触发父组件的函数 在父组件里关闭弹层和追加评论
        this.$emit('pub-comment', res.data.new_obj)
        // 2、清空文本框
        this.message = ''
        // 3、追加到评论列表 在父组件处理
        this.$toast.success('评论成功')
      } catch (err) {
        // console.log('发布失败', err)
        this.$toast.fail('发布失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.comment-pub {
  display: flex;
  align-items: center;
  padding: 32px 0 32px 32px;
  .post-field {
    background-color: #f5f7f9;
  }
  .post-btn {
    width: 150px;
    border: none;
    padding: 0;
    color: #6ba3d8;
    background: #fff;
    &::before {
      display: none;
    }
  }
}
</style>
